<?php

namespace App\Admin\Metrics\Home;

use Dcat\Admin\Widgets\Metrics\Line;
use Illuminate\Http\Request;
use App\Models\User;
class NewUsers extends Line
{
    protected $chartHeight = 180;
    /**
     * 初始化卡片内容
     *
     * @return void
     */
    protected function init()
    {
        parent::init();

        $this->title('客户新增数量');
        $this->dropdown([
            '7' => 'Last 7 Days',
            // '28' => 'Last 28 Days',
            '30' => 'Last Month',
            '365' => 'Last Year',
        ]);
        $this->height(290);
    }

    /**
     * 处理请求
     *
     * @param Request $request
     *
     * @return mixed|void
     */
    public function handle(Request $request)
    {
        
        switch ($request->get('option')) {
            case '365':
                $nums = User::selectRaw("DATE_FORMAT(created_at,'%Y-%m') AS date, count(id) as count")->whereDate('created_at', '>', now()->subDays(30)->toDateTimeString())->groupBy('date')->pluck('count')->toArray();

                // 图表数据
                $this->withChart($nums);
                break;
            case '30':
                $nums = User::selectRaw("DATE(created_at) AS date, count(id) as count")->whereDate('created_at', '>', now()->subDays(30)->toDateTimeString())->groupBy('date')->pluck('count')->toArray();
                // 图表数据
                $this->withChart($nums);
                break;
            case '28':
                // 图表数据
                $this->withChart(collect($generator(28))->toArray());
                break;
            case '7':
            default:
                // 卡片内容
                $nums = User::selectRaw("DATE(created_at) AS date, count(id) as count")->whereDate('created_at', '>', now()->subDays(7)->toDateTimeString())->groupBy('date')->pluck('count')->toArray();
                // 图表数据
                $this->withChart($nums);
        }
        // 卡片内容
        $user_num = User::where('created_at', '>=', now()->subDays($request->get('option'))->toDateTimeString())->count();
        $this->withContent($user_num);
    }

    /**
     * 设置图表数据.
     *
     * @param array $data
     *
     * @return $this
     */
    public function withChart(array $data)
    {
        return $this->chart([
            'series' => [
                [
                    'name' => $this->title,
                    'data' => $data,
                ],
            ],
        ]);
    }

    /**
     * 设置卡片内容.
     *
     * @param string $content
     *
     * @return $this
     */
    public function withContent($content)
    {
        return $this->content(
            <<<HTML
<div class="d-flex justify-content-between align-items-center mt-1" style="margin-bottom: 2px">
    <h2 class="ml-1 font-lg-1">{$content}</h2>
    <span class="mb-0 mr-1 text-80">{$this->title}</span>
</div>
HTML
        );
    }
}
